package lol.clann.bukkit.pluginboot.config.jackson.nbt;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lol.clann.bukkit.pluginboot.util.NBTUtils;
import lol.clann.clannboot.annotation.inject.Inject;
import lol.clann.clannboot.annotation.svc.PostInstance;
import lol.clann.clannboot.annotation.svc.Service;
import lol.clann.clannboot.config.jackson.Jackson;
import lol.clann.clannboot.util.clazz.WrapClass;

import java.io.IOException;

/**
 * @author pyz
 * @date 2018/10/12 上午12:11
 */
@Service(priority = Integer.MAX_VALUE - 100)
public class NBTSerializerRegister {

    @Inject
    private NBTUtils nbtUtils;

    @PostInstance
    private void init() {
        Jackson.addSerializer(NBTUtils.classNBTTagCompound.getHandle(), new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                Object v = nbtUtils.getValue(value);
                if (v == null) {
                    gen.writeNull();
                } else {
                    gen.writeObject(v);
                }
            }
        });

        Jackson.addSerializer(NBTUtils.classNBTTagList.getHandle(), new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                Object v = nbtUtils.getValue(value);
                if (v == null) {
                    gen.writeNull();
                } else {
                    gen.writeObject(v);
                }
            }
        });
        register(NBTUtils.classNBTTagByte);
        register(NBTUtils.classNBTTagByteArray);
        register(NBTUtils.classNBTTagShort);
        register(NBTUtils.classNBTTagInt);
        register(NBTUtils.classNBTTagIntArray);
        register(NBTUtils.classNBTTagLong);
        if (NBTUtils.supportNBTTagLongArray) {
            register(NBTUtils.classNBTTagLongArray);
        }
        register(NBTUtils.classNBTTagFloat);
        register(NBTUtils.classNBTTagDouble);
        register(NBTUtils.classNBTTagString);
    }

    private void register(WrapClass type) {
        Jackson.addSerializer(type.getHandle(), new JsonSerializer<Object>() {
            private NBTConventorNode convertor;
            private Class nbtType = type.getHandle();

            private NBTConventorNode getConvertor() {
                if (convertor == null) {
                    convertor = NBTUtils.getByClass(nbtType);
                }
                return convertor;
            }

            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeString(getConvertor().getKey() + getConvertor().getSerializer().apply(value));
            }
        });
    }
}
